/*
 * @author zzr
 * @date: 2025/05/08  21:40
 * @description: 实现一个 Timer 计时器
 */

import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask> {
    // time 表示什么时候执行任务
    private long time;
    private Runnable runnable;

    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        time = System.currentTimeMillis() + delay;
    }

    public void run() {
        runnable.run();
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }

    public long getTime() {
        return time;
    }
}

class MyTimer {

    private Thread thead;
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimerTask timerTask = new MyTimerTask(runnable, delay);
            queue.offer(timerTask);
            locker.notify();
        }
    }

    public MyTimer() {
        thead = new Thread(() -> {
            while (true) {
                synchronized (locker) {
                    try {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask timerTask = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= timerTask.getTime()) {
                            queue.poll();
                            timerTask.run();
                        } else {
                            locker.wait(curTime - timerTask.getTime());
                            curTime = System.currentTimeMillis(); // 注意这里需要重新获取时间~
                            if (curTime >= timerTask.getTime()) {
                                queue.poll();
                                timerTask.run();
                            }
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        thead.start();
    }
}

public class Demo8 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
    }
}
